﻿using System;
using System.Collections.Generic;
using System.Linq;
using SoftSource.Timecard.Web.Data;

namespace SoftSource.Timecard.Web.DAL
{
    public class Projects
    {
        public static Project GetProjectByID(int projectID)
        {
            using (ProjectDBDataContext db = Utilities.GenerateProjectDataContext())
            {
                var project = from p in db.Projects
                              where p.ProjectID == projectID
                              select p;
                return project.SingleOrDefault();
            }
        }

        public static IEnumerable<int> GetProjectsForUser(int userID)
        {
            using (ProjectDBDataContext db = Utilities.GenerateProjectDataContext())
            {
                var projectIDs = from p in db.Projects
                                 join pm in db.ProjectMembers on p.ProjectID equals pm.ProjectID
                                 where pm.UserID == userID
                                 select p.ProjectID;
                return projectIDs.ToList().Distinct();
            }
        }

        public static IEnumerable<int> GetManagingProjects(int userID)
        {
            using (ProjectDBDataContext db = Utilities.GenerateProjectDataContext())
            {
                return db.Projects
                    .Where(p => p.ManagerUserID == userID)
                    .Select(p => p.ProjectID)
                    .Distinct()
                    .ToList();
            }
        }
        
        public static DateTime GetProjectCreationDate(int projectID)
        {
            using (ProjectDBDataContext db = Utilities.GenerateProjectDataContext())
            {
                var creationDate = from p in db.Projects
                                   where p.ProjectID == projectID
                                   select p.CreationDate;

                return creationDate
                    .ToList()
                    .SingleOrDefault();
            }
        }
    }
}
